package com.myjob.controller;

import com.alibaba.fastjson.JSONObject;
import com.myjob.config.PrivateKeyProperties;
import com.myjob.entity.User;
import com.myjob.exception.OptionException;
import com.myjob.handlerImpl.AuthHandler;
import com.myjob.response.Result;
import com.myjob.service.LoginService;
import com.myjob.utils.RSAUtils;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;

/**
 * @author chenyuan
 * @date 2020/12/26 21:48
 */

@Slf4j
@RestController
@RequestMapping("/account/LOrR")
public class LoginController {
	@Autowired
	private LoginService loginService;
	@Autowired
	private AuthHandler authHandler;
	@Autowired
	private PrivateKeyProperties privateKey;

	private final String GRANT_TYPE = "password";
	private final String CLIENT_SECRET = "secret";
	private final String CLIENT_ID = "myjob";

	@PostMapping("/loginWithPassword")
	public Result loginWithPassword(@RequestParam("userName") String userName,
	                                @RequestParam("encodedPassword") String encodedPassword){
		if (UtilValidate.isEmpty(userName) ||
				UtilValidate.isEmpty(encodedPassword)) {
			return Result.failed("用户名 或 密码为空");
		}
		Result result = null;
		try {
			encodedPassword = encodedPassword.replace(" ", "+");
			String password = RSAUtils.decryptRSADefault(privateKey.getPrivateKey(), encodedPassword);
			Integer loginResult = loginService.loginWithPassword(userName, password);

			if (loginResult == 1){
				HashMap<String, String> map = new HashMap<>();
				map.put("grant_type", GRANT_TYPE);
				map.put("client_secret", CLIENT_SECRET);
				map.put("client_id", CLIENT_ID);
				map.put("username", userName);
				map.put("password", password);

				String token = authHandler.getToken(new Principal() {
					@Override
					public String getName() {
						return "myjob";
					}
				}, map);
				result = JSONObject.parseObject(token, Result.class);
			}else if (loginResult == -1){
				result = Result.failed("用户名不存在");
			}else if (loginResult == -2){
				result = Result.failed("密码错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("登录异常");
		}
		return result;
	}

	@PostMapping("/loginWithCode")
	public Result loginWithCode(@RequestParam("userName") String userName,
	                                @RequestParam("code") String code){
		if (UtilValidate.isEmpty(userName) ||
				UtilValidate.isEmpty(code)) {
			return Result.failed("邮箱 或 验证码为空");
		}
		Result result = null;
		try {
			HashMap<String, String> resultMap = new HashMap<>();
			Integer loginResult = loginService.loginWithCode(userName, code, resultMap);
			String password = resultMap.get("password");
			log.info("password: " + password);

			if (loginResult == 1){
				HashMap<String, String> map = new HashMap<>();
				map.put("grant_type", GRANT_TYPE);
				map.put("client_secret", CLIENT_SECRET);
				map.put("client_id", CLIENT_ID);
				map.put("username", userName+"##");
				map.put("password", password);

				String token = authHandler.getToken(new Principal() {
					@Override
					public String getName() {
						return "myjob";
					}
				}, map);
				result = JSONObject.parseObject(token, Result.class);
			}else if (loginResult == -1){
				result = Result.warn("邮箱不存在");
			}else if (loginResult == -2){
				result = Result.failed("验证码已过期过期,请重新获取");
			}else if (loginResult == -3){
				result = Result.failed("验证码输入错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("登录异常");
		}
		return result;
	}

	@GetMapping("/phoneIsExist")
	public Result phoneIsExist(String phone) {
		Result result = null;
		try {
			Boolean isExist = loginService.phoneIsExist(phone);
			if (isExist){
				result = Result.failed("该手机号已存在");
			}else {
				result = Result.succeed("该手机号可使用");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("手机号查重异常");
		}
		return result;
	}

	@GetMapping("/emailIsExist")
	public Result emailIsExist(String email) {
		Result result = null;
		try {
			Boolean isExist = loginService.emailIsExist(email);
			if (isExist){
				result = Result.failed("该邮箱已存在");
			}else {
				result = Result.succeed("该邮箱可使用");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("邮箱查重异常");
		}
		return result;
	}

	@GetMapping("/sendCode")
	public Result sendCode(@RequestParam("phoneNumber") String phoneNumber){
		Result result = null;
		try {
			String code = loginService.sendCode(phoneNumber);
			if (UtilValidate.isNotEmpty(code)) {
				result = Result.succeed(code, "验证码已发送");
			}else {
				result = Result.failed("获取验证码异常");
			}
		}catch (Exception e){
		    e.printStackTrace();
		    throw new OptionException("生成验证码异常");
		}
		return result;
	}

	@PostMapping("/registerAccount")
	public Result registerAccount(@RequestBody User user){
		Result result = null;
		try {
			if (UtilValidate.isEmpty(user)) {
				return Result.failed("注册参数为空");
			}


			String password = user.getPassword();
			password = RSAUtils.decryptRSADefault(privateKey.getPrivateKey(), password);
			user.setPassword(password);

			Boolean register = loginService.registerAccount(user);
			if (register){
				result = Result.succeed("注册成功,请至登录页登录");
			}else {
				result = Result.failed("注册出错,请刷新重试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("注册账户异常");
		}
		return result;
	}
}
